package org.noranj.me.client;
 
import java.io.File;
import java.io.InputStream;
import java.net.URL;

import javax.xml.transform.stream.StreamSource;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.io.CachedOutputStream;

public class RunMe {
  
  public static void main(String args[]) throws Exception {
    delete();
  }
  
  private static void aboutMe() throws Exception {
    URL url = new URL("http://localhost:9000/conversation/about");
    InputStream in = url.openStream();
    System.out.print(getStringFromInputStream(in).toString());

  }
  
  private static void simpleGet() throws Exception {
    System.out.println("Sent HTTP GET request to query user info");
    URL url = new URL("http://localhost:9000/conversation/conversations");
    InputStream in = url.openStream();
    System.out.println(getStringFromInputStream(in));
    } 
  
  
  private static void add() throws Exception {
    // Sent HTTP POST request to add user
    RunMe client = new RunMe();
    System.out.println("\n");
    System.out.println("Sent HTTP POST request to add user");
    String inputFile = client.getClass().getResource("add_user.xml").getFile();
    File input = new File(inputFile);
    HttpPost post = new HttpPost("http://localhost:9000/conversation/addrow");
    post.addHeader("Accept" , "text/xml");
    HttpEntity entity = new FileEntity(input, "text/xml; charset=ISO-8859-1");
    post.setEntity(entity);
    HttpClient httpclient = new DefaultHttpClient();

    try {
      HttpResponse result = httpclient.execute(post);
        System.out.println("Response status code: " + result.getStatusLine());
        System.out.println("Response body: ");
        System.out.println(getStringFromInputStream(result.getEntity().getContent()));
    } finally {
        // Release current connection to the connection pool once you are
        // done
    }

  }
  
  private static void delete() throws Exception {
    URL url = new URL("http://localhost:9000/conversation/deleteall");
    InputStream in = url.openStream();
    System.out.print(getStringFromInputStream(in).toString());
  }
  
  private static String getStringFromInputStream(InputStream in) throws Exception {
    CachedOutputStream bos = new CachedOutputStream();
    IOUtils.copy(in, bos);
    in.close();
    bos.close();
    return ">>>>\r\n"+bos.getOut().toString()+"\r\n-----------------------------------------------------------";
  }
}
